function [begp,endp,n]=sync(x)

%% const
deafregion = 32;

%% program
deaf = 0;
y=ditch(x);
ilastpulse = -1;

currbegp = 0;
currendp = 0;
strength = 0;
interval = 0;
psv_begp = 0;
psv_endp = 0;
psv_strength = 0;
psv_interval = 0;

for i = 1 : length(y)
    if deaf
        deaf = i-ilastpulse < deafregion;
    end

    if deaf
        continue;
    end
    
    if y(i) == 1
        if ilastpulse > 0
            d = i - ilastpulse;
            if interval > 0
                %% interval captured
                mul=appx(d,interval,0.05);
                if mul
                    interval = interval * strength;
                    interval = interval + d;
                    strength = strength + mul;
                    interval = interval / strength;
                    
                    currendp = i;
                else
                    % newer interval takes place
                    if strength > psv_strength
                        psv_interval = interval;
                        psv_strength = strength;
                        psv_begp = currbegp;
                        psv_endp = currendp;
                    end
                    
                    interval = d;
                    strength = 1;
                    currbegp = ilastpulse;
                end
            else
                %% interval not captured (first time)
                interval = d;
                strength = 1;
                currbegp = ilastpulse;
            end % interval > 0
        end % ilastpulse > 0
        
        ilastpulse=i;
        deaf = 1;
    end % if y(i) == 1
end % for

if strength > psv_strength
    begp = currbegp;
    endp = currendp;
    n = strength;
else
    begp = psv_begp;
    endp = psv_endp;
    n = psv_strength;
end

